<template>
  <div class="consult">
    <!-- 搜索栏 -->
    <div class="nav">
      <el-input
        v-model="input"
        placeholder="请输入内容"
        style="width: 500px; margin-right: 30px"
      ></el-input>
      <el-button type="primary" @click="selectVisible">搜索</el-button>
    </div>

    <!-- 添加按钮 -->
    <el-button type="primary" @click="insertVisible = true" style="margin-bottom: 20px;">添加+</el-button>

    <!-- 知识列表表格 -->
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column
        prop="id"
        label="id"
        width="80"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="knowlegeName"
        label="标题"
        width="180"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="knowlegeIntro"
        label="简介"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="picture"
        label="图片"
        width="150"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <div class="img-container" @click="showImage(scope.row.picture)">
            <img :src="scope.row.picture" />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="knowlegeContent"
        label="详情"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="uploadVis(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 图片放大对话框 -->
    <el-dialog :visible.sync="dialogVisible" width="30%">
      <img :src="tableData.image" alt="大图" style="width: 100%" />
    </el-dialog>

    <!-- 新增知识对话框 -->
    <el-dialog title="新增" :visible.sync="insertVisible" width="60%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="form.knowlegeName"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="form.knowlegeIntro"></el-input>
        </el-form-item>
        <!-- 文件上传 -->
        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/course/fileup"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            style="width: 150px; height: 150px"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="详情">
          <el-input type="textarea" v-model="form.knowlegeContent"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click="insertVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑知识对话框 -->
    <el-dialog title="修改" :visible.sync="updateVisible" width="60%">
      <el-form ref="form" :model="update" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="update.knowlegeName"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="update.knowlegeIntro"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/course/fileup"
            :show-file-list="false"
            :on-success="handleAvatarSuccessU"
            :before-upload="beforeAvatarUploadU"
            style="width: 150px; height: 150px"
          >
            <img v-if="this.update.picture" :src="this.update.picture" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情">
          <el-input type="textarea" v-model="update.knowlegeContent"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onUpdated">立即创建</el-button>
          <el-button @click="updateVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页控件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formLabelWidth: "120px",
      allData: [],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      dialogVisible: false,
      insertVisible: false,
      input: "",
      form: {
        id: "",
        knowlegeName: "",
        knowlegeIntro: "",
        picture: "",
        knowlegeContent: "",
      },
      update: {
        id: "",
        knowlegeName: "",
        knowlegeIntro: "",
        picture: "",
        knowlegeContent: "",
      },
      updateVisible: false,
      imageUrl: "",

      //临时id
      temporaryId:'',
    };
  },
  methods: {
    // 获取所有知识数据
    queryAllarticle() {
      this.axios
        .get("http://localhost:8080/knowledge/getKnowledges")
        .then((res) => {
          this.allData = res.data.data;
          this.total = this.allData.length;
          this.getTabelData();
        })
        .catch((err) => console.log(err));
    },

    // 显示大图
    showImage(imageUrl) {
      this.tableData.image = imageUrl;
      this.dialogVisible = true;
    },

    // 获取分页数据
    getTabelData() {
      const start = (this.pageNum - 1) * this.pageSize;
      const end = this.pageNum * this.pageSize;
      this.tableData = this.allData.slice(start, end);
    },

    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTabelData();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getTabelData();
    },

    // 提交新增知识
    onSubmit() {
      this.insertVisible = false;
      this.axios
        .post("http://localhost:8080/knowledge/addKnowlege", this.form)
        .then((res) => {
          this.allData = res.data.data;
          this.total = this.allData.length;
          this.queryAllarticle();
        })
        .catch((err) => console.log(err));
    },
    //修改
    uploadVis(row) {
      this.updateVisible = true;
      this.temporaryId=row.id;
      this.axios
        .get(`http://localhost:8080//knowledge/getKnowlegeById`, {
          params: { id: row.id },
        })
        .then((res) => {
          console.log(res);
          this.update = res.data.data;
        })
        .catch((err) => console.log(err));
    },
    //确认修改
    onUpdated() {
      console.log(this.update);
      
      this.axios
        .put("http://localhost:8080/knowledge/updateKnowlege", this.update)
        .then((res) => {
          this.queryAllarticle();
          this.allData = res.data.data;
          this.total = this.allData.length;
        })
        .catch((err) => console.log(err));
        this.updateVisible=false;
     
    },

    // 搜索知识
    selectVisible() {
      this.axios
        .get("http://localhost:8080/knowledge/getKnowledgeByTitle", {
          params: { knowlegeName: this.input },
        })
        .then((res) => {
          this.allData = res.data.data;
          this.total = this.allData.length;
          this.getTabelData();
        })
        .catch((err) => console.log(err));
    },

    // 处理删除操作
    handleDelete(row) {
      this.$confirm("确认删除这条知识记录吗？", "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteKnowledge(row.id);
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },

    // 执行删除知识
    deleteKnowledge(id) {
      const headers = {
        "Content-Type": "application/json",
        Authorization: "Bearer " + localStorage.getItem("token"), // 如果需要认证
        "Custom-Header": "Some-Value", // 任何其他自定义头部
      };
      this.axios
        .delete(`http://localhost:8080/knowledge/removeKnowlege/${id}`, {
          headers,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功");
            this.pageNum=1;
            this.queryAllarticle(); // 重新加载数据
          } else {
            this.$message.error("删除失败: " + res.data.message);
          }
        })
        .catch((err) => {
          console.error("删除请求失败:", err);
          this.$message.error("删除请求失败，请稍后重试");
        });
    },
    // 文件上传
    // 返回图片的地址
    handleAvatarSuccess(res, file) {
      this.form.picture =
        "http://localhost:8080/course/downImg?file=" + file.response.data;
      console.log(this.form.picture);
    },

    beforeAvatarUpload(file) {
      this.imageUrl = URL.createObjectURL(file);
    },
    //更改文件
    handleAvatarSuccessU(res, file) {
      this.update.picture =
        "http://localhost:8080/course/downImg?file=" + file.response.data;
      console.log(this.update.picture);
    },

    beforeAvatarUploadU(file) {
      this.update.picture = URL.createObjectURL(file);
    },
  },
  created() {
    this.queryAllarticle();
  },
};
</script>

<style>
.nav {
  display: flex;
  flex-wrap: nowrap;
  margin-bottom: 30px;
}
.img-container {
  width: 100px;
  height: 100px;
  position: relative;
  border-radius: 20%;
  overflow: hidden;
  cursor: pointer;
}
.img-container > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}




.avatar-uploader{
  margin-bottom: 20px;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>